package com.powersi.demo.servlet;

import com.powercloud.rhea.stat.RheaStatServiceImpl;
import com.powercloud.rhea.utils.RheaBeanUtil;
import com.powersi.demo.DemoService;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * @author mg
 * @title: InvokeServlet
 * @projectName pomparent
 * @description: TODO
 * @date 2019/8/3114:51
 */
public class InvokeServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;


    private RheaStatServiceImpl statService = RheaStatServiceImpl.getInstance();

    public InvokeServlet() {
    }

    public void init() throws ServletException {
        super.init();



    }

    @Override
    public void service(ServletRequest r, ServletResponse p) throws ServletException ,IOException{

        HttpServletRequest request = (HttpServletRequest)r;
        HttpServletResponse response= (HttpServletResponse)p;
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");

        writeResult(request, response); //回写结果
    }

    /**
     * 输出返回对象到访问者
     * @param request
     * @param response
     * @throws IOException
     */
    private void writeResult( HttpServletRequest request, HttpServletResponse response) throws IOException{
        String say = request.getParameter("say");
        ServletOutputStream out = response.getOutputStream();
        OutputStreamWriter ow = new OutputStreamWriter(out);
        try {
            DemoService targetService = RheaBeanUtil.getBean( "demoService" );
            String result = targetService.saySomething("I am consumer, I say "+ say);
            ow.write(result);
        }finally {
            ow.flush();
            ow.close();
        }

    }
}
